//
//  BaiKeMainViewController.m
//  BaseProject
//
//  Created by 王洋 on 2020/12/10.
//  Copyright © 2020 王洋. All rights reserved.
//

#import "BaiKeMainViewController.h"
#import "BaiKeMainSearchView.h"
#import "BSTBitmapView.h"
#import "BaiKeMainModel.h"
#import "BaiKeMainCell.h"
#import "BaiKeMainSectionHeaderView.h"
#import "BaiKeMainTableViewHeaderView.h"
//刷新
#import "AnimRefreshHeader.h"
#import "AnimRefreshFooter.h"
//跳转
#import "BaiKeSecondClassesVC.h"
#import "BaiKeSecondClassesItemVC.h"
#import "BaiKeDetailVC.h"
@interface BaiKeMainViewController ()<UITableViewDelegate,UITableViewDataSource,BSTBitmapViewDelegate,BaiKeMainSectionHeaderViewDelegate>
@property(nonatomic,strong)BaiKeMainSearchView *searchView;
@property(nonatomic,strong)UITableView *mainView;
@property(nonatomic,assign)NSInteger pageIndex;
@property(nonatomic,assign)NSInteger pageNumber;
@property(nonatomic,strong)BSTBitmapView *bitmapView;
@property(nonatomic,strong)NSMutableArray<BaiKeSubListDataListModel *> *dataSource;
@property(nonatomic,strong)BaiKeMainTableViewHeaderView *tableHeaderView;
@end

@implementation BaiKeMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createProperty];
    [self createUI];
    [self createNetMethod];
}
- (void)createProperty
{
    //屏幕常亮
    [UIApplication sharedApplication].idleTimerDisabled = YES;
    self.navigationController.navigationBarHidden = YES;
    #if RT_INTERACTIVE_PUSH
        self.rt_navigationController.rt_enableInteractivePush = YES;
    #endif
    self.pageIndex = 1;
    self.pageNumber = 1000;
}
- (void)createUI
{
    [self searchView];
    [self mainView];
    self.bitmapView.top = 0;
    self.bitmapView.type = BitmapViewTypeLoading;
}
#pragma mark - 网络请求
- (void)createNetMethod
{
    [self createRefresh];
}
- (void)createRefresh
{
    self.mainView.mj_header = [AnimRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    [self loadNewData];//静态刷新
    //[self.mainView.mj_header beginRefreshing];
}
//下拉刷新
- (void)loadNewData
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //恢复可刷新状态
        if (self.mainView.mj_footer) {
            [self.mainView.mj_footer removeFromSuperview];
        }
        [self endRefresh];
        //star
        self.pageIndex = 1;
        [self loadMyMessage];
    });
}
//上拉加载
- (void)loadMoreData
{
    self.pageIndex ++;
    [self loadMyMessage];
}
- (void)loadMyMessage
{
    WK(weakSelf)
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [TTHttpManager postRequestWithUrl:[NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,@"/userWeddingEncyclopedia/queryWedIndex"] TimeOut:10 PostData:parameters FinishBlock:^(id  _Nonnull responseObject) {
        BaiKeMainModel *responModel = [BaiKeMainModel modelWithJSON:responseObject];
        if (responModel.success) {
            if (weakSelf.pageIndex == 1)
            {
                //--------------头部刷新--------------//
                [weakSelf refreshHeadCode:responModel];
                //处理没有数据的占位图
                [weakSelf refreshNoDataBitMapView];
            } else {
                //--------------脚部刷新--------------//
                [weakSelf refreshFooterCode:responModel];
            }
        } else {
            [SVProgressHUD showWithStatus:responModel.message];
            [SVProgressHUD dismissWithDelay:1];
        }
    } FailedBlock:^(NSError * _Nonnull error) {
        [SVProgressHUD showWithStatus:@"请检查网络~"];
        [SVProgressHUD dismissWithDelay:1];
    }];
}
- (void)endRefresh
{
    if (self.mainView.mj_header) {
        [self.mainView.mj_header endRefreshing];
    }
    if (self.mainView.mj_header) {
        [self.mainView.mj_footer endRefreshing];
    }
}
- (NSArray *)handleData:(BaiKeMainModel *)dataModel
{
    for (NSInteger index = 0; index < dataModel.data.classes.count; index ++) {
        dataModel.data.classes[index].oneName = dataModel.data.classes[index].parentName;
    }
    for (NSInteger index = 0; index < dataModel.data.weddingEncyclopedias.count; index ++) {
        BaiKeSubListDataListModel *listModel = dataModel.data.weddingEncyclopedias[index];
        NSMutableAttributedString *titleAttributes = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@",listModel.briefIntroduction]];
        titleAttributes.font = kFontRegular13;
        titleAttributes.color = rgba(102, 102, 102, 1);
        titleAttributes.lineSpacing = 5*ADAPTER_WIDTH;
        listModel.introductionHeight = [YYTextLayout layoutWithContainerSize:CGSizeMake(WIDTH - 52*ADAPTER_WIDTH, MAXFLOAT) text:titleAttributes].textBoundingSize.height;
        listModel.introductionHeight = MIN(56*ADAPTER_WIDTH, listModel.introductionHeight);
        listModel.cellHeight = listModel.introductionHeight + 59*ADAPTER_WIDTH;//14+35+10
        listModel.briefIntroduction_attributes = titleAttributes;
        listModel.createTime = @"";
    }
    return dataModel.data.weddingEncyclopedias;
}
- (void)refreshHeadCode:(BaiKeMainModel *)dataModel
{
    [self.dataSource removeAllObjects];
    [self.dataSource addObjectsFromArray:[self handleData:dataModel]];
    //加载头部之类的
    self.tableHeaderView.mainModel = dataModel;
    self.mainView.tableHeaderView = self.tableHeaderView;
    //刷新mainView
    [self.mainView reloadData];
    [self endRefresh];
    //添加脚步刷新 会自动销毁替换的
    dispatch_async(dispatch_get_main_queue(), ^{
        //1.如果分页数量满额的
        //  1.1 如果contentSize.height 大与自身 则需要加入脚步
        //  1.2 如果contentSize.height 小与自身 则不需要加入脚步 请求下一个接口
        //2.如果分页数量小于满额
        //  2.1  如果contentSize.height 大与自身 则需要加入脚步 提醒没有更多了
        //  2.2  如果contentSize.height 小于自身 则不需要加入脚步
        //3.如果是0
        //  3.1  直接移除脚步 一个cell都没有要脚步干啥
        if (dataModel.data.weddingEncyclopedias.count >= self.pageNumber) {
            if (self.mainView.contentSize.height > self.mainView.height) {
                MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
                self.mainView.mj_footer = footer;
            } else {
                [self loadMoreData];
            }
        } else if (dataModel.data.weddingEncyclopedias.count > 0){
            if (self.mainView.contentSize.height > self.mainView.height) {
                MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
                [footer endRefreshingWithNoMoreData];
                self.mainView.mj_footer = footer;
            } else {
                if (self.mainView.mj_footer) {
                    [self.mainView.mj_footer removeFromSuperview];
                }
            }
        } else {
            if (self.mainView.mj_footer) {
                [self.mainView.mj_footer removeFromSuperview];
            }
        }
    });
}
- (void)refreshFooterCode:(BaiKeMainModel *)dataModel
{
    [self.dataSource addObjectsFromArray:[self handleData:dataModel]];
    if (dataModel.data.weddingEncyclopedias.count > 0) {
        [self.mainView reloadData];
        [self endRefresh];
    }
    //1.如果分页数量满额的 无需处理
    //  1.1 如果contentSize.height 大与自身  无任何操作
    //  1.2 如果contentSize.height 小与自身  请求下个接口
    //2.如果分页数量小于满额
    //  2.1  如果contentSize.height 大与自身  提醒没有更多了
    //  2.2  如果contentSize.height 小于自身 则不需要加入脚步
    dispatch_async(dispatch_get_main_queue(), ^{
        if (dataModel.data.weddingEncyclopedias.count >= self.pageNumber) {
            if (self.mainView.contentSize.height > self.mainView.height) {
                MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
                self.mainView.mj_footer = footer;
            } else {
                [self loadMoreData];
            }
        } else {
            if (self.mainView.contentSize.height > self.mainView.height) {
                [self.mainView.mj_footer endRefreshingWithNoMoreData];
            } else {
                if (self.mainView.mj_footer) {
                    [self.mainView.mj_footer removeFromSuperview];
                }
            }
        }
    });
}
#pragma mark - 占位图
- (void)refreshNoDataBitMapView
{
    //占位图
    if (self.dataSource.count == 0) {
        self.bitmapView.type = BitmapViewTypeNoData;
        [self.mainView addSubview:self.bitmapView];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.bitmapView.frame = self.mainView.bounds;
            self.bitmapView.origin = CGPointMake(0, self.mainView.tableHeaderView.height);
        });
    } else {
        self.bitmapView.type = BitmapViewTypeNormal;
        [self.view insertSubview:self.bitmapView belowSubview:self.mainView];
        dispatch_async(dispatch_get_main_queue(), ^{
             //留着扩大滑动范围用
            self.bitmapView.frame = self.mainView.frame;
        });
    }
}
- (void)refreshNetErrorBitMapView
{
    if (self.dataSource.count == 0) {
        self.bitmapView.type = BitmapViewTypeNetError;
        [self.mainView addSubview:self.bitmapView];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.bitmapView.frame = self.mainView.bounds;
            self.bitmapView.origin = CGPointMake(0, self.mainView.tableHeaderView.height);
        });
    } else {
        self.bitmapView.type = BitmapViewTypeNormal;
        [self.view insertSubview:self.bitmapView belowSubview:self.mainView];
        dispatch_async(dispatch_get_main_queue(), ^{
             //留着扩大滑动范围用
            self.bitmapView.frame = self.mainView.frame;
        });
    }
}
#pragma mark - BSTBitmapView代理
- (void)bstBitmapView:(BSTBitmapView *)bitmapView backType:(BitmapViewType)type
{
    if (type == BitmapViewTypeLoading) {
        NSLog(@"加载中....");
    } else if (type == BitmapViewTypeNetError || type == BitmapViewTypeServerCrash) {
        NSLog(@"网络错误");
        [self loadNewData];
    } else if (type == BitmapViewTypeNoData) {
        NSLog(@"没有数据");
        [self loadNewData];
    }
}
#pragma mark - UITableView代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataSource.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BaiKeMainCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.listModel = self.dataSource[indexPath.section];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.dataSource[indexPath.section].cellHeight;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    BaiKeMainSectionHeaderView *view = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"sectionHeader"];
    view.listModel = self.dataSource[section];
    view.section = section;
    view.delegate = self;
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 37*ADAPTER_WIDTH;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return [[UIView alloc]init];
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    BaiKeDetailVC *vc = [[BaiKeDetailVC alloc]init];
    vc.listModel = self.dataSource[indexPath.section];
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark - BaiKeMainSectionHeaderViewDelegate
- (void)baiKeMainSectionHeaderViewSection:(NSInteger)section backType:(NSInteger)type
{
    BaiKeSecondClassesItemVC *vc = [[BaiKeSecondClassesItemVC alloc]init];
    BaiKeMainClassesDataModel *listModel = [[BaiKeMainClassesDataModel alloc]init];
    listModel.scId = self.dataSource[section].threeId;
    listModel.threeName = self.dataSource[section].threeName;
    vc.type = BaiKeSecondClassesItemVCTypeThreeList;
    vc.listModel = listModel;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark - lazy懒加载
- (BaiKeMainSearchView *)searchView
{
    if (!_searchView) {
        BaiKeMainSearchView *view = [[BaiKeMainSearchView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, kTopHeight)];
        [self.view addSubview:view];
        view.parentVC = (BaseVC *)self;
        _searchView = view;
    }
    return _searchView;
}
- (UITableView *)mainView
{
    if (!_mainView) {
        UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kTopHeight, WIDTH, HEIGHT - kTopHeight - TabBar_Height) style:UITableViewStyleGrouped];
        [self.view addSubview:tableView];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.tableFooterView = [UIView new];
        [tableView registerClass:[BaiKeMainCell class] forCellReuseIdentifier:@"Cell"];
        [tableView registerClass:[BaiKeMainSectionHeaderView class] forHeaderFooterViewReuseIdentifier:@"sectionHeader"];
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.backgroundColor = [UIColor whiteColor];
        if (@available(iOS 11.0, *))
        {
            tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            tableView.estimatedRowHeight = 0;
            tableView.estimatedSectionFooterHeight = 0;
            tableView.estimatedSectionHeaderHeight = 0;
        }
        else
        {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        _mainView = tableView;
    }
    return _mainView;
}
- (BSTBitmapView *)bitmapView
{
    if (!_bitmapView) {
        BSTBitmapView *view = [[BSTBitmapView alloc]initWithFrame:CGRectMake(0, 0, self.mainView.width, self.mainView.height)];
        [self.mainView addSubview:view];
        view.delegate = self;
        _bitmapView = view;
    }
    return _bitmapView;
}
- (NSMutableArray<BaiKeSubListDataListModel *> *)dataSource
{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}
- (BaiKeMainTableViewHeaderView *)tableHeaderView
{
    if (!_tableHeaderView) {
        BaiKeMainTableViewHeaderView *view = [[BaiKeMainTableViewHeaderView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 190*ADAPTER_WIDTH)];
        view.parentVC = self;
        _tableHeaderView = view;
    }
    return _tableHeaderView;
}
@end
